﻿using System;
using DDDNorthWind.AC.Products.Domain.DomainEvents;
using DDDNorthWind.AC.Products.Domain.Services;
using DDDNorthWind.Core.Domain.EventArgs;
using DDDNorthWind.Core.MessageHandler;

namespace DDDNorthWind.AC.Products.Handler
{
    public class AsignarMedidasAProductoHandler : MessageHandler<IAssignSizeMessage>
    {
        private readonly IProductServices productServices;

        public override void Dispose()
        {
            UnRegisterEvents();
            productServices.Dispose();
        }

        private void UnRegisterEvents()
        {
            productServices.ProductSizeChanged -= OnProductSizeChanged;
        }

        public AsignarMedidasAProductoHandler(IProductServices productServices)
        {
            this.productServices = productServices;
            RegisterEvents();
        }

        private void RegisterEvents()
        {
            productServices.ProductSizeChanged += OnProductSizeChanged;
        }

        private void OnProductSizeChanged(object sender, EventAppliedEventArgs<ProductSizedChanged> e)
        {
            //NewSizeReadModel
            Bus.WithMessage(null).AsAsync().Send();
        }

        public override void Handler(IAssignSizeMessage command)
        {
            productServices.AssignImportSizes(command.ProductId, command.High, command.Length, command.Width);
        }
    }
}